# -*- coding: utf-8 -*-
'''
@文件    :aioredis.py
@说明    :redis的异步封装
@时间    :2025/08/25 17:21:53
@作者    :浪晋
@版本    :1.0
'''
from typing import List, Optional
from redis import asyncio as aioredis



class AIORedis:
    def __init__(self, username: str = "defualt", password: str = "", host: str = "loaclhost", port: int = 6379, db: int = 0, decode: bool = True):
        self.user = username
        self.pwd = password
        self.host = host
        self.port = port
        self.db = db
        self.decode = decode

    async def get(self, key) -> Optional[str]:
        return await self.pool.get(key)
    
    async def keys(self, key) -> List:
        return await self.pool.keys(key)
    
    async def mget(self, keys: List) -> List:
        return await self.pool.mget(keys)
    
    async def set(self, key, value, ex=None):
        return await self.pool.set(key, value, ex)

    async def delete(self, *keys):
        return await self.pool.delete(*keys)

    async def startup(self):
        """创建连接池"""
        url = f"redis://{self.user}:{self.pwd}@{self.host}:{self.port}/{self.db}"
        self.pool = aioredis.from_url(
            url=url,
            encoding="utf-8",
            decode_responses=self.decode
        )

    async def shutdown(self):
        """关闭连接池"""
        await self.pool.aclose()

if __name__ == "__main__":
    import asyncio

    async def demo():
        redis = AIORedis("")
        res = await redis.get("name")
        print(res)
    
    asyncio.run(demo())